package com.hgy.controller;

import com.hgy.common.JsonResult;
import com.hgy.dao.UserDao;
import com.hgy.entity.User;
import com.hgy.service.UserService;
import com.hgy.utils.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserService userService;

    @RequestMapping("/register.do")
    @ResponseBody
    public JsonResult register(User user) {

        JsonResult jsonResult = null;
        try {
            userService.addUser(user);
            jsonResult = new JsonResult(1, "注册成功");
        } catch (Exception e) {
            jsonResult = new JsonResult(0, "注册失败");
        }

        return jsonResult;
    }

    @RequestMapping("/login.do")
    @ResponseBody
    public JsonResult login(String tel, String password, HttpSession session) {
        User user = userService.login(tel, password);
        session.setAttribute(StrUtils.LOGIN_USER, user);
        JsonResult jsonResult = new JsonResult(1, null);
        return jsonResult;
    }

    @RequestMapping("/denglu.do")
    @ResponseBody
    public JsonResult denglu(HttpSession session) {
        User user = (User) session.getAttribute(StrUtils.LOGIN_USER);
        User byId = userDao.findById(user.getId());
        if (byId == null) {
            return new JsonResult(0, "用户未登录");
        } else {
            return new JsonResult(1, byId);
        }
    }

    @RequestMapping("/update.do")
    @ResponseBody
    public JsonResult updateUser(String tel, HttpSession session) {
        User user = (User) session.getAttribute(StrUtils.LOGIN_USER);
        userService.updateUser(user.getId(), tel);
        return new JsonResult(1, "修改成功");
    }
}
